package com.lb.shopguide.ui.dialog;

import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.base.DialogBase;
import com.lb.shopguide.GuideApplication;
import com.lb.shopguide.R;
import com.lb.shopguide.adapter.tag.AdapterFlowTagRec;
import com.lb.shopguide.constants.AppConstant;
import com.lb.shopguide.entity.recommend.RecSkuBean;
import com.lb.shopguide.entity.recommend.RecommendDetailGoodsBean;
import com.lb.shopguide.ui.view.flowlayout.Attribute;
import com.lb.shopguide.ui.view.flowlayout.FlowLayout;
import com.lb.shopguide.ui.view.flowlayout.TagAdapter;
import com.lb.shopguide.ui.view.flowlayout.TagFlowLayout;
import com.lb.shopguide.util.lb.BizGoodsUtil;
import com.lb.shopguide.util.pic.ImageLoaderUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by kang on 2017/6/13.
 */

public class DialogSelectRecSku extends DialogBase implements View.OnClickListener {
    private ImageView ivGoods;
    //    private TextView tvGoods;
    private TextView tvPrice;
    private TextView tvShare;
    private TextView tvSpec1;
    private TextView tvSpec2;
    private TextView tvTips;
    private ImageView ivClose;
    private TagFlowLayout layoutOne;
    private TagFlowLayout layoutTwo;
    private LinearLayout layoutEarnMoney;
    private TextView tvEarnMoney;
    private TextView tvOrgPrice;

    private RecommendDetailGoodsBean mGoodsDetailBean;
    private ArrayList<RecSkuBean> mSkuList;

    private Attribute sizeAttr = new Attribute();
    private Attribute colorAttr = new Attribute();
    private List<String> mSizeList;//大小属性数据
    private List<String> mColorList;//颜色属性数据
    private List<String> mFailureSkuList;//无库存或不能选的所有组合sku
    private List<String> mAllSkuList;//所有的组合sku
    private int curColor;//临时记录的颜色
    private int curSize;//临时记录的大小

    private String spec2;
    private String spec1;

    private AdapterFlowTagRec mSizeAdapter;
    private AdapterFlowTagRec mColorAdapter;

    private boolean isSaleOut;

    public static DialogSelectRecSku getDialogSelectSku(RecommendDetailGoodsBean bean) {
        DialogSelectRecSku dialogSelectSku = new DialogSelectRecSku();
        Bundle bundle = new Bundle();
        bundle.putSerializable(AppConstant.GOODS_DETAIL_BEAN, bean);
        dialogSelectSku.setArguments(bundle);
        return dialogSelectSku;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View mFragmentView = inflater.inflate(R.layout.dialog_select_rec_sku, container, false);
        initData();
        initView(mFragmentView);

        setDialogPosition();
        return mFragmentView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(STYLE_NO_TITLE, R.style.dialog_bottom_rec);
    }

    private void setDialogPosition() {
        Window window = getDialog().getWindow();
        window.setGravity(Gravity.BOTTOM | Gravity.FILL_HORIZONTAL);
    }

    private void initData() {
        mSkuList = new ArrayList<>();
        mColorList = new ArrayList<>();
        mSizeList = new ArrayList<>();
        mFailureSkuList = new ArrayList<>();
        mAllSkuList = new ArrayList<>();
        Bundle bundle = getArguments();
        if (bundle.containsKey(AppConstant.GOODS_DETAIL_BEAN)) {
            mGoodsDetailBean = (RecommendDetailGoodsBean) bundle.getSerializable(AppConstant.GOODS_DETAIL_BEAN);
            mSkuList = (ArrayList<RecSkuBean>) mGoodsDetailBean.getSkuList();
        }
    }

    private void initView(View view) {
        ivGoods = view.findViewById(R.id.iv_product);
//        tvGoods = view.findViewById(R.id.tv_product_name);
        ivClose = view.findViewById(R.id.iv_close);
        tvPrice = view.findViewById(R.id.tv_price);
        tvShare = view.findViewById(R.id.tv_share);
        layoutTwo = view.findViewById(R.id.layout_color);
        layoutOne = view.findViewById(R.id.layout_size);
        tvSpec1 = view.findViewById(R.id.tv_spec_1);
        tvSpec2 = view.findViewById(R.id.tv_spec_2);
        tvTips = view.findViewById(R.id.tv_tips);
        layoutEarnMoney = view.findViewById(R.id.layout_earn_money);
        tvEarnMoney = view.findViewById(R.id.tv_earn_price);
        tvOrgPrice = view.findViewById(R.id.tv_origin_price);

        bindData();
        initListener();
    }


    private void bindData() {
//        tvGoods.setText(mGoodsDetailBean.getProductName());

        tvSpec1.setText(mGoodsDetailBean.getSpecName1());
        tvSpec2.setText(mGoodsDetailBean.getSpecName2());
        if (mGoodsDetailBean.isSecSymbol()) {
            tvTips.setVisibility(View.VISIBLE);
            layoutEarnMoney.setVisibility(View.GONE);
        } else {
            tvTips.setVisibility(View.GONE);
            layoutEarnMoney.setVisibility(View.VISIBLE);
        }
        tvEarnMoney.setText("￥" + mGoodsDetailBean.getStaffBen());
        tvPrice.setText("￥" + mGoodsDetailBean.getSalePrice());
        tvOrgPrice.setText("￥" + mGoodsDetailBean.getOrgPrice());
        tvOrgPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        bindSku();
        if (mGoodsDetailBean.isSecSymbol()) {
            if (mGoodsDetailBean.getSecStatus() == AppConstant.GOODS_SEC_END) {
                isSaleOut = true;
            }
        }
        if (mGoodsDetailBean.getTotalStoreSum() == 0) {
            isSaleOut = true;
        }
        if (mGoodsDetailBean.isSecSymbol()) {
            if (mGoodsDetailBean.getSecStatus() == AppConstant.GOODS_SEC_NOT_START) {
                tvShare.setBackgroundResource(R.drawable.bg_goods_share_first);
                tvShare.setText("先去分享,秒杀快人一步。");
            }
        }
        if (isSaleOut) {//显示已售空
            tvShare.setText("已售空");
            tvShare.setBackgroundResource(R.drawable.bg_goods_sale_out);
        }
    }

    private void bindSku() {
        List result = BizGoodsUtil.getSpec12InDialog(mSkuList);
        //第一个是尺寸，第二个是颜色
        Map<String, String> mapSize = (Map<String, String>) result.get(0);
        Map<String, String> mapColor = (Map<String, String>) result.get(1);
        mSizeList.addAll(mapSize.keySet());
        sizeAttr.aliasName.addAll(mSizeList);
        mColorList.addAll(mapColor.keySet());
        colorAttr.aliasName.addAll(mColorList);

        for (RecSkuBean skuBean : mSkuList) {
            if (skuBean.isDefault()) {
                setRecSkuBean(skuBean);
                ImageLoaderUtils.getGlideManager().asBitmap().load(skuBean.getSkuPicUrl()).into(ivGoods);
            }
        }
        if (TextUtils.isEmpty(spec1) && TextUtils.isEmpty(spec2)) {
            if (mSizeList.size() == 0 || mColorList.size() == 0) {

            } else {
                spec1 = mSizeList.get(0);
                spec2 = mColorList.get(0);
            }
        }

        RecSkuBean curRecSkuBean = BizGoodsUtil.getCurRecSkuBean(spec1, spec2, mSkuList);
        if (curRecSkuBean != null) {
            selectSku(curRecSkuBean);
        }

        for (Map.Entry<String, String> entryColor : mapColor.entrySet()) {
            for (Map.Entry<String, String> entrySize : mapSize.entrySet()) {
                mAllSkuList.add(entryColor.getKey() + ":" + entrySize.getKey());
                RecSkuBean skuBean = BizGoodsUtil.getCurRecSkuBean(entrySize.getKey(), entryColor.getKey(), mSkuList);
                if (skuBean == null) {
                    mFailureSkuList.add(entryColor.getKey() + ":" + entrySize.getKey());
                }
            }
        }
        mSizeAdapter = new AdapterFlowTagRec(GuideApplication.getAppContext(), sizeAttr);
        layoutOne.setAdapter(mSizeAdapter);
        for (int i = 0; i < mSizeList.size(); i++) {
            if (spec1.equals(mSizeList.get(i))) {
                mSizeAdapter.setSelectedList(i);
            }
        }
        mColorAdapter = new AdapterFlowTagRec(GuideApplication.getAppContext(), colorAttr);
        layoutTwo.setAdapter(mColorAdapter);
        for (int i = 0; i < mColorList.size(); i++) {
            if (spec2.equals(mColorList.get(i))) {
                mColorAdapter.setSelectedList(i);
            }
        }
        //颜色属性标签点击事件
        layoutTwo.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            boolean unableFlag;

            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                unableFlag = false;
                //从Base类中拿到不可点击的属性名称进行比较
                List<String> st = colorAttr.getFailureAliasName();
                for (int i = 0; i < st.size(); i++) {
                    if (st.get(i).equals(mColorList.get(position))) {
                        unableFlag = true;
                    }
                }
                //如是不可点击就进接return 这样就形成了不可点击的假像，达到了我们的目的
                if (unableFlag) {
                    return true;
                }
                if (position == curColor) {
                    curColor = -1;
                    spec2 = "";
                    sizeAttr.failureAliasName.clear();
                    notifyColorAndSize();
                    return true;
                } else {
                    curColor = position;
                    spec2 = mColorList.get(position);
                }
                RecSkuBean skuBean = BizGoodsUtil.getCurRecSkuBean(spec1, spec2, mSkuList);
                if (skuBean != null) {
                    selectSku(skuBean);
                }
                sizeAttr.failureAliasName.clear();
                for (int i = 0; i < mSizeList.size(); i++) {
                    String sku = spec2 + ":" + mSizeList.get(i);
                    for (int j = 0; j < mFailureSkuList.size(); j++) {
                        if (sku.equals(mFailureSkuList.get(j))) {
                            sizeAttr.failureAliasName.add(mSizeList.get(i));
                        }
                    }
                }
                notifyColorAndSize();
                return true;
            }
        });


        //大小属性标签点击事件
        layoutOne.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            boolean unableFlag;

            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                unableFlag = false;
                List<String> st = sizeAttr.getFailureAliasName();
                for (int i = 0; i < st.size(); i++) {
                    if (st.get(i).equals(mSizeList.get(position))) {
                        unableFlag = true;
                    }
                }
                if (unableFlag) {
                    return true;
                }
                if (position == curSize) {
                    curSize = -1;
                    spec1 = "";
                    colorAttr.failureAliasName.clear();
                    notifyColorAndSize();
                    return true;
                } else {
                    curSize = position;
                    spec1 = mSizeList.get(position);
                }
                RecSkuBean skuBean = BizGoodsUtil.getCurRecSkuBean(spec1, spec2, mSkuList);
                if (skuBean != null) {
                    selectSku(skuBean);
                }
                colorAttr.failureAliasName.clear();
                for (int i = 0; i < mColorList.size(); i++) {
                    String sku = mColorList.get(i) + ":" + spec1;
                    for (int j = 0; j < mFailureSkuList.size(); j++) {
                        if (sku.equals(mFailureSkuList.get(j))) {
                            colorAttr.failureAliasName.add(mColorList.get(i));
                        }
                    }
                }
                notifyColorAndSize();
                return true;
            }
        });
    }

    private void initListener() {
        tvShare.setOnClickListener(this);
        ivClose.setOnClickListener(this);
    }

    private void setRecSkuBean(RecSkuBean skuBean) {
        spec1 = skuBean.getSpecAttr1();
        spec2 = skuBean.getSpecAttr2();
    }

    private void notifyColorAndSize() {
        notifyTagAdapterChange(mColorAdapter, curColor);
        notifyTagAdapterChange(mSizeAdapter, curSize);
    }

    public void notifyTagAdapterChange(TagAdapter Adapter, int CcInt) {
        Adapter.getPreCheckedList().clear();
        if (CcInt != -1) {
            Adapter.setSelectedList(CcInt);
        }
        Adapter.notifyDataChanged();
    }

    private void selectSku(RecSkuBean skuBean) {
        if (skuBean != null) {
            ImageLoaderUtils.getGlideManager().asBitmap().load(skuBean.getSkuPicUrl())
                    .apply(ImageLoaderUtils.getSGCommonGlideOption(4)).into(ivGoods);
            tvPrice.setText("￥" + skuBean.getSalePrice());
            tvOrgPrice.setText("￥" + skuBean.getOrgPrice());
        } else {
            ToastUtils.showShort("请检查该商品颜色尺码，重新选择");
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_share:
                if (TextUtils.isEmpty(spec2)) {
                    ToastUtils.showShort("请选择颜色");
                    return;
                }
                if (TextUtils.isEmpty(spec1)) {
                    ToastUtils.showShort("请选择尺寸");
                    return;
                }
                if (!isSaleOut && mOnShareClickListener != null) {
                    mOnShareClickListener.onShareClickListener();
                    DialogSelectRecSku.this.dismissAllowingStateLoss();
                }
                break;
            case R.id.iv_close:
                DialogSelectRecSku.this.dismissAllowingStateLoss();
                break;
        }
    }

    private OnShareClickListener mOnShareClickListener;

    public interface OnShareClickListener {
        void onShareClickListener();
    }

    public void setOnShareClickListener(OnShareClickListener listener) {
        mOnShareClickListener = listener;
    }
}
